package com.pixeljet.html5.client;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Widget;

/**
 * https://developer.mozilla.org/En/DragDrop/Drag_Operations
 * 
 * @author Jason
 * 
 */
public class DropEnabler {

	private static Map<Element, DropCallback> map = new HashMap<Element, DropCallback>();

	public DropEnabler() {

	}

	@SuppressWarnings("unused")
	private static void handleLoad(Element element, File file, String base64data) {
		map.get(element).onDrop(file);
	}
	
	
	public static void registerForDrop(Element element, DropCallback callback) {
		setupNativeDrop(element);
		map.put(element, callback);
	}

	public static void registerForDrop(Widget widget, DropCallback callback) {
		registerForDrop(widget.getElement(), callback);
	}
	
	native static void setupNativeDrop(Element element) /*-{
		handleDrop = function (event) {
			event.stopPropagation();
			event.preventDefault();
			var files = event.dataTransfer.files;
			
			for (var i = 0; i < files.length; i++ ) {
				var file = files[i];
				var b64reader = new FileReader();
				b64reader.onloadend = (function(file) { return function(base64) {
					file.base64data = base64.target.result;
					@com.pixeljet.html5.client.DropEnabler::handleLoad(Lcom/google/gwt/user/client/Element;Lcom/pixeljet/html5/client/File;Ljava/lang/String;)(element, file, base64.target.result);
				}; })(file);  

				b64reader.readAsDataURL(file);
			}
		};
		element.addEventListener("dragenter", function(event){event.stopPropagation();event.preventDefault();}, false);
		element.addEventListener("dragover", function(event){event.stopPropagation(); event.preventDefault();}, false);
		element.addEventListener("drop", handleDrop, false);
		
	}-*/;

}
